package com.ruoyi.course.controller;

import java.util.*;
import jakarta.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.domain.vo.CourseSchedulingIinquiryVo;
import com.ruoyi.student.domain.vo.RegInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.course.domain.vo.TimetableVO;
import com.ruoyi.course.domain.vo.CourseInfoVO;
import com.ruoyi.student.service.impl.StudentInfoServiceImpl;
import com.ruoyi.teacher.domain.teacher;
import com.ruoyi.teacher.mapper.teacherMapper;
import com.ruoyi.teacher.service.IteacherService;
import com.ruoyi.trainingManagement.domain.ClassScheduleDetailed;
import com.ruoyi.trainingManagement.domain.CourseAdjustmentRecord;
import com.ruoyi.trainingManagement.domain.CourseScheduleDetails;
import com.ruoyi.trainingManagement.domain.Vo.CourseAndTimeVo;
import com.ruoyi.trainingManagement.mapper.ClassScheduleDetailedMapper;
import com.ruoyi.trainingManagement.mapper.CourseStudentInfoMapper;
import com.ruoyi.trainingManagement.service.IClassScheduleDetailedService;
import com.ruoyi.trainingManagement.service.ICourseAdjustmentRecordService;
import com.ruoyi.trainingManagement.service.ICourseScheduleDetailsService;
import com.ruoyi.trainingManagement.service.ICourseStudentInfoService;
import com.ruoyi.trainingManagement.service.impl.CourseStudentInfoServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.domain.ResourceAvailability;
import com.ruoyi.course.service.IResourceAvailabilityService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.student.service.IStudentInfoService;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.trainingManagement.domain.Vo.ClassScheduleVo;
import com.ruoyi.trainingManagement.mapper.CourseAdjustmentRecordMapper;
import com.ruoyi.trainingManagement.mapper.CourseScheduleDetailsMapper;
/**
 * 资源可用时间Controller
 * 
 * @author chenxl
 * @date 2025-06-29
 */
@RestController
@RequestMapping("/course/availability")
public class ResourceAvailabilityController extends BaseController
{
    @Autowired
    private IResourceAvailabilityService resourceAvailabilityService;

    @Autowired
    private ICourseStudentInfoService CourseStudentInfoService;

    @Autowired
    private IClassScheduleDetailedService classScheduleDetailedService;

    @Autowired
    private ICourseScheduleDetailsService courseScheduleDetailsService;
    @Autowired
    private StudentInfoServiceImpl studentInfoServiceImpl;
    @Autowired
    private IteacherService teacherService;
    //teacherMapper
    @Autowired
    private teacherMapper teacherMapper;
    @Autowired
    private ClassScheduleDetailedMapper classScheduleDetailedMapper;
    @Autowired
    private ICourseAdjustmentRecordService courseAdjustmentRecordService;
    @Autowired
    private SysDeptServiceImpl sysDeptService;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private IStudentInfoService studentInfoService;
    @Autowired
    private CourseScheduleDetailsMapper courseScheduleDetailsMapper;
    @Autowired
    private CourseAdjustmentRecordMapper courseAdjustmentRecordMapper;

    /**
     * 查询资源可用时间列表
     */
    //@PreAuthorize("@ss.hasPermi('course:availability:list')")
    @GetMapping("/list")
    public TableDataInfo list(ResourceAvailability resourceAvailability)
    {
        startPage();
        List<ResourceAvailability> list = resourceAvailabilityService.selectResourceAvailabilityList(resourceAvailability);
        return getDataTable(list);
    }

    /**
     * 导出资源可用时间列表
     */
    @PreAuthorize("@ss.hasPermi('course:availability:export')")
    @Log(title = "资源可用时间", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResourceAvailability resourceAvailability)
    {
        List<ResourceAvailability> list = resourceAvailabilityService.selectResourceAvailabilityList(resourceAvailability);
        ExcelUtil<ResourceAvailability> util = new ExcelUtil<ResourceAvailability>(ResourceAvailability.class);
        util.exportExcel(response, list, "资源可用时间数据");
    }

    /**
     * 获取资源可用时间详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:availability:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(resourceAvailabilityService.selectResourceAvailabilityById(id));
    }

    /**
     * 新增资源可用时间
     */
    @PreAuthorize("@ss.hasPermi('course:availability:add')")
    @Log(title = "资源可用时间", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResourceAvailability resourceAvailability)
    {
        return toAjax(resourceAvailabilityService.insertResourceAvailability(resourceAvailability));
    }

    /**
     * 修改资源可用时间
     */
    @PreAuthorize("@ss.hasPermi('course:availability:edit')")
    @Log(title = "资源可用时间", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResourceAvailability resourceAvailability)
    {
        return toAjax(resourceAvailabilityService.updateResourceAvailability(resourceAvailability));
    }

    /**
     * 删除资源可用时间
     */
    @PreAuthorize("@ss.hasPermi('course:availability:remove')")
    @Log(title = "资源可用时间", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(resourceAvailabilityService.deleteResourceAvailabilityByIds(ids));
    }

    @GetMapping("/timetable")
    public R getTimetable(@RequestParam String resourceId,
                          @RequestParam String academicYear) {
        //打印获取到的 数据
        System.out.println("---------开始查询课程表----------");
        System.out.println("资源ID：" + resourceId + "学年：" + academicYear);
        System.out.println("------------------------------");
        TimetableVO timetable = resourceAvailabilityService.getResourceTimetable(resourceId, academicYear);
        return R.ok().put("data", timetable);
    }


    @GetMapping("/student-timetable")
    public R getStudentTimetable(@RequestParam String courseScheduleDetailsId) {
        try {
            System.out.println("开始查询开班课程" + courseScheduleDetailsId);
            List<String> studentIds = CourseStudentInfoService.selectStudentIdsByCourseScheduleDetailsId(courseScheduleDetailsId);
            //打印获取到的名单
            System.out.println("获取到的名单为: " + studentIds);
            // 处理学生ID列表为空的情况
            if (studentIds == null || studentIds.isEmpty()) {
                // 返回空的时间表结构，而不是抛出异常
                TimetableVO emptyTimetable = new TimetableVO();
                emptyTimetable.setWeekdays(Collections.emptyList());
                return R.ok("该课程暂无学生选课记录")
                        .put("data", emptyTimetable);
            }

            TimetableVO timetableVO = resourceAvailabilityService.selectClassSchedulesByStudentIds(studentIds);
            System.out.println("---------开始查询学生课表----------");
            System.out.println("获取到的时间表为: " + timetableVO);
            System.out.println("---------结束查询学生课表----------");
            return R.ok().put("data", timetableVO);
        } catch (Exception e) {
            // 统一异常处理，避免直接抛出到前端
//            log.error("查询学生课表失败", e);
            System.out.println("查询学生课表失败");
            return R.fail().put("msg", "查询学生课表失败：" + e.getMessage());
        }

    }

    /**
     * 提交或更新课程信息
     * 接收前端提交的课程信息并保存到数据库，同时生成资源占用记录
     *
     * @param courseInfoVO 课程信息VO对象，包含完整的课程详情
     * @return 操作结果
     */
    @RequestMapping(value = "/submitCourseInfo", method = RequestMethod.PUT)
    public AjaxResult submitCourseInfo(@RequestBody CourseInfoVO courseInfoVO) {
        try {
            // 1. 打印前端传递的课程信息
            System.out.println("---------开始提交课程信息0902----------");
            System.out.println("获取数据: " + courseInfoVO);

            // 2. 校验必要参数
            if (courseInfoVO == null || StringUtils.isEmpty(courseInfoVO.getCourseId())) {
                return AjaxResult.error("课程ID不能为空");
            }
            if (CollectionUtils.isEmpty(courseInfoVO.getCourseSchedule())) {
                return AjaxResult.error("课程时间安排不能为空");
            }

            // 校验课程详细信息列表及其中的ID
            if (CollectionUtils.isEmpty(courseInfoVO.getCourseScheduleDetails())) {
                return AjaxResult.error("课程详细信息不能为空");
            }
            // 获取course_schedule_details_id（从课程详细信息中提取）
            String courseScheduleDetailsId = courseInfoVO.getCourseScheduleDetails().get(0).getId();
            if (StringUtils.isEmpty(courseScheduleDetailsId)) {
                return AjaxResult.error("课程详情ID（course_schedule_details_id）不能为空");
            }
            System.out.println("获取到的course_schedule_details_id: " + courseScheduleDetailsId);

            // 3. 获取基础数据
            String courseId = courseInfoVO.getCourseId();
            //String teacherId = courseInfoVO.getTeacherId();          // 教师ID
            String classroomId = courseInfoVO.getClassroomId();      // 教室ID
            Integer startWeek = courseInfoVO.getStartWeek();         // 开始周
            Integer endWeek = courseInfoVO.getEndWeek();             // 结束周
            Integer semesterId = courseInfoVO.getSemesterId();       // 学期ID
            String academicYear = String.valueOf(courseInfoVO.getAcademicYear());    // 学年
            System.out.println("获取数据: " + academicYear);

            // 4. 处理课程详细信息 - 调用update方法更新数据库
            List<CourseScheduleDetails> detailsList = courseInfoVO.getCourseScheduleDetails();
            for (CourseScheduleDetails details : detailsList) {
                // 确保关联ID正确（如果前端未传递，这里补充设置）
                if (StringUtils.isEmpty(details.getCourseId())) {
                    details.setCourseId(courseId);
                }
                // 补充其他必要字段（根据实际业务需求）
                details.setStartWeek(Long.valueOf(startWeek));
                details.setEndWeek(Long.valueOf(endWeek));
                details.setUpdatedAt(new Date()); // 更新时间
                details.setIsScheduleCompleted(1L);
                details.setClassroom(classroomId);

                // 调用Service层方法更新课程详细表
                int updateRows = courseScheduleDetailsService.updateCourseScheduleDetails(details);
                System.out.println("更新课程详细信息，ID: " + details.getId() + "，影响行数: " + updateRows);
            }

            // 5. 获取学生名单（使用course_schedule_details_id查询）
            List<String> studentIds = CourseStudentInfoService.selectStudentIdsByCourseScheduleDetailsId(courseScheduleDetailsId);
            System.out.println("获取到的名单为: " + studentIds);

            // 6. 准备资源占用记录列表
            List<ResourceAvailability> records = new ArrayList<>();

            // 7. 处理课程时间段记录并保存到class_schedule_detailed表
            for (CourseInfoVO.CourseScheduleDTO schedule : courseInfoVO.getCourseSchedule()) {
                ClassScheduleDetailed classScheduleDetailed = new ClassScheduleDetailed();
                classScheduleDetailed.setId(UUID.randomUUID().toString());
                // 关联课程详情ID
                classScheduleDetailed.setCourseScheduleDetailsId(courseScheduleDetailsId);
                classScheduleDetailed.setStartTime("第" + schedule.getStart() + "节");
                classScheduleDetailed.setEndTime("第" + schedule.getEnd() + "节");
                classScheduleDetailed.setWeekDay((long)schedule.getXq());
                classScheduleDetailed.setLessonCount(Long.valueOf(courseInfoVO.getLessonsPerClass()));
                classScheduleDetailed.setWeekType(Long.valueOf(courseInfoVO.getCoursePeriod()));

                classScheduleDetailedService.insertClassScheduleDetailed(classScheduleDetailed);
            }
            List<String> teacherIds =courseInfoVO.getTeacherId();
            //循环列表取出教师id
            for (String teacherId : teacherIds){
                // 8. 处理教师资源（类型1）- 传入course_schedule_details_id
                if (StringUtils.isNotEmpty(teacherId)) {
                    System.out.println("获取到的教师ID为: " + teacherId);
                    records.addAll(createResourceRecords(
                            1,  // 资源类型：教师
                            teacherId,
                            courseInfoVO.getCourseSchedule(),
                            startWeek,
                            endWeek,
                            semesterId,
                            academicYear,
                            "课程安排占用",
                            courseScheduleDetailsId  // 传入课程详情ID
                    ));
                }
            }
            // 9. 处理教室资源（类型2）- 传入course_schedule_details_id
            if (StringUtils.isNotEmpty(classroomId)) {
                records.addAll(createResourceRecords(
                        2,  // 资源类型：教室
                        classroomId,
                        courseInfoVO.getCourseSchedule(),
                        startWeek,
                        endWeek,
                        semesterId,
                        academicYear,
                        "课程安排占用",
                        courseScheduleDetailsId  // 传入课程详情ID
                ));
            }

            // 10. 处理学生资源（类型3）- 传入course_schedule_details_id
            if (CollectionUtils.isNotEmpty(studentIds)) {
                for (String studentId : studentIds) {
                    records.addAll(createResourceRecords(
                            3,  // 资源类型：学生
                            studentId,
                            courseInfoVO.getCourseSchedule(),
                            startWeek,
                            endWeek,
                            semesterId,
                            academicYear,
                            "课程安排占用",
                            courseScheduleDetailsId  // 传入课程详情ID
                    ));
                }
            }

            // 11. 批量保存资源占用记录
            if (!records.isEmpty()) {
                resourceAvailabilityService.batchInsertResourceAvailability(records);
            }

            return AjaxResult.success("课程班信息提交成功，共生成" + records.size() + "条资源占用记录，关联course_schedule_details_id: " + courseScheduleDetailsId);
        } catch (Exception e) {
            logger.error("提交课程信息失败", e);
            return AjaxResult.error("服务器错误：" + e.getMessage());
        }
    }


    /**
     * 创建资源占用记录
     * @param resourceType 资源类型（1=教师，2=教室，3=学生）
     * @param resourceId 资源ID
     * @param schedules 课程时间段列表
     * @param startWeek 开始周
     * @param endWeek 结束周
     * @param semesterId 学期ID
     * @param academicYear 学年
     * @param reason 占用原因
     * @param courseScheduleDetailsId 课程详情ID（新增参数）
     * @return 资源占用记录列表
     */
    private List<ResourceAvailability> createResourceRecords(
            int resourceType,
            String resourceId,
            List<CourseInfoVO.CourseScheduleDTO> schedules,
            Integer startWeek,
            Integer endWeek,
            Integer semesterId,
            String academicYear,
            String reason,
            String courseScheduleDetailsId) {  // 新增参数：课程详情ID
        System.out.println("创建资源占用记录，课程班ID：" + courseScheduleDetailsId);
        List<ResourceAvailability> records = new ArrayList<>();
        // 星期中文映射（用于重复规则）
        Map<Integer, String> weekMap = new HashMap<>();
        weekMap.put(1, "周一");
        weekMap.put(2, "周二");
        weekMap.put(3, "周三");
        weekMap.put(4, "周四");
        weekMap.put(5, "周五");
        weekMap.put(6, "周六");
        weekMap.put(7, "周日");

        // 遍历每个时间段，生成记录
        for (CourseInfoVO.CourseScheduleDTO schedule : schedules) {
            ResourceAvailability record = new ResourceAvailability();
            record.setId(UUID.randomUUID().toString());  // 生成唯一ID
            // 新增：设置课程详情ID关联
            record.setCourseScheduleDetailsId(courseScheduleDetailsId);
            record.setResourceType((long)resourceType);
            record.setResourceId(resourceId);
            record.setDayOfWeek(schedule.getXq());  // 周几（1-7）
            record.setStartTime("第" + schedule.getStart() + "节");  // 开始节次
            record.setEndTime("第" + schedule.getEnd() + "节");      // 结束节次
            record.setSemesterId(semesterId != null ? semesterId.longValue() : null);  // 安全转换
            record.setAcademicYear(academicYear);
            // 重复规则：每周x，第startWeek-endWeek周
            record.setRepeatRule(String.format("每周%s（第%d-%d周）",
                    weekMap.getOrDefault(schedule.getXq(), "未知"), startWeek, endWeek));
            record.setIsAvailable(0);  // 0=不可用（被占用）
            record.setReason(reason);
            record.setRemark("自动生成的课程占用记录");

            records.add(record);
        }
        return records;
    }

    /**
     * 通过教师ID查询全部学期课程详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:availability:query')")
    @GetMapping("/teacher/{teacherId}")
    public R getCoursesByTeacherId(@PathVariable("teacherId") String teacherId) {
        System.out.println("获取到的teacherId: " + teacherId);
        try {
            // 参数校验
            if (StringUtils.isEmpty(teacherId)) {
                return R.fail("教师ID不能为空");
            }

            // 查询教师相关的资源占用记录（教师作为资源类型1）
            ResourceAvailability queryParam = new ResourceAvailability();
            queryParam.setResourceId(teacherId);
            //queryParam.setResourceType(1L); // 1=教师资源类型
            List<ResourceAvailability> resourceList = resourceAvailabilityService.selectResourceAvailabilityList(queryParam);

            if (CollectionUtils.isEmpty(resourceList)) {
                return R.ok("该教师暂无课程安排").put("data", Collections.emptyList());
            }

            // 收集所有相关的课程ID并去重
            Set<String> courseIdSet = new HashSet<>();
            for (ResourceAvailability resource : resourceList) {
                // 假设资源记录中通过remark字段关联了课程ID（实际应根据表结构调整）
                if (StringUtils.isNotEmpty(resource.getRemark()) && resource.getRemark().startsWith("课程ID:")) {
                    String courseId = resource.getRemark().replace("课程ID:", "").trim();
                    courseIdSet.add(courseId);
                }
            }

            // 查询课程详细信息
            List<CourseScheduleDetails> courseList = new ArrayList<>();
            if (!courseIdSet.isEmpty()) {
                CourseScheduleDetails courseQuery = new CourseScheduleDetails();
                for (String courseId : courseIdSet) {
                    courseQuery.setId(courseId);
                    courseQuery.setTeacherId(teacherId);
                    List<CourseScheduleDetails> courses = courseScheduleDetailsService.selectCourseScheduleDetailsList(courseQuery);
                    if (CollectionUtils.isNotEmpty(courses)) {
                        courseList.addAll(courses);
                    }
                }
            }

//            // 补充课程的详细时间安排
//            for (CourseScheduleDetails course : courseList) {
//                List<ClassScheduleDetailed> timeDetails = classScheduleDetailedService
//                        .selectClassScheduleDetailedByCourseId(course.getId());
//                course.setTimeDetails(timeDetails);
//            }

            return R.ok().put("data", courseList);
        } catch (Exception e) {
            logger.error("查询教师课程信息失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    //根据用户登录信息查询对应的课表(不用了)
    @RequestMapping(value = "/getCourseTable", method = RequestMethod.GET)
    public AjaxResult getCourseTable() {
        // 获取当前登录用户
        LoginUser user = SecurityUtils.getLoginUser();
        System.out.println("获取到的user: " + user);
        if (user == null) {
            return AjaxResult.error("未获取到登录用户信息");
        }
        // 获取当前登录IP地址
        RegInfo regInfo = new RegInfo();
        StudentInfo studentInfo = studentInfoServiceImpl.selectStudentInfoByStudentId(user.getUsername());
        System.out.println(studentInfo);
        String academicYear = String.valueOf(0);
        TimetableVO timetable = resourceAvailabilityService.getResourceTimetable(studentInfo.getId(), academicYear);
        System.out.println("studentInfo.getId(): " + studentInfo.getId());
        return AjaxResult.success(timetable);
    }
    //selectByResourceIdAndResourceType
    @RequestMapping(value = "/selectByResourceIdAndResourceType", method = RequestMethod.GET)
    public R selectByResourceIdAndResourceType(@RequestParam String resourceId) {
        System.out.println("获取到的resourceId: " + resourceId);
        int resourceType = 1;
        List<String> teacherName=new ArrayList<>();
        List<ResourceAvailability> resourceAvailabilityList = resourceAvailabilityService.selectByResourceIdAndAcademicYear(resourceId, resourceType);
        for (ResourceAvailability resourceAvailability : resourceAvailabilityList){
            String teacher =resourceAvailability.getResourceId();
            System.out.println("获取到的teacher: " + teacher);
            teacherName.add(teacherMapper.selectteacherByUuid(teacher).getName());
        }
        System.out.println("获取到的teacherName: " + teacherName);
        //返回teacherName
        return R.ok(teacherName);
    }
    //selectCourseSchedulingIinquiryListByTeacherId
    @GetMapping("/selectCourseSchedulingIinquiryListByTeacherId")
    public AjaxResult selectCourseSchedulingIinquiryListByTeacherId(){
        // 获取当前登录用户
        LoginUser user = SecurityUtils.getLoginUser();
        System.out.println("获取到的user: " + user);
        if (user == null) {
            return AjaxResult.error("未获取到登录用户信息");
        }
        String teacherId =teacherMapper.selectteacherIdByTeacherCode(user.getUsername());
        System.out.println("查询条件: " + user.getUsername());
        System.out.println("查询结果: " + teacherId);

        if (teacherId == null) {
            return AjaxResult.error("未找到对应的教师信息");
        }

        // 使用学生ID查询课程安排
        List<CourseSchedulingIinquiryVo> courseScheduleDetails =
                resourceAvailabilityService.selectCourseSchedulingIinquiryListByTeacherId(teacherId);

        return AjaxResult.success(courseScheduleDetails);
    }
    /**
     * 通过教师ID获取对应的全部课程班及时间安排信息00
     * @param
     * @return 课程班信息及时间安排列表
     */
    //@PreAuthorize("@ss.hasPermi('trainingManagement:details:query')")
    @GetMapping("/getCourseScheduleDetailsByTeacherId00")
    public List<CourseAndTimeVo> getCourseScheduleDetailsByTeacherId00() {
        LoginUser user = SecurityUtils.getLoginUser();
        String teacherId = "";
        teacherId = user.getUsername();
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的teacherId-----: " + teacherId);
        teacher teacher =new teacher();
        teacher.setTeacherCode(teacherId);
        List<teacher> teacherList = teacherMapper.selectteacherList(teacher);
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的teacherList: " + teacherList);
        teacher teacher1 = teacherList.get(0);
        String teacherId1 = teacher1.getUuid();
        System.out.println("getCourseScheduleDetailsByTeacherId00-----获取到的teacherId1: " + teacherId1);
        System.out.println("获取到的user: " + user);
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的teacherId: " + teacherId1);
        List<String> courseScheduleDetailsId = resourceAvailabilityService.selectCourseScheduleDetailsIdByResourceId(teacherId1);
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的courseScheduleDetailsId: " + courseScheduleDetailsId);
        List<CourseScheduleDetails> courseScheduleDetailsList =courseScheduleDetailsService.selectCourseScheduleDetailsByIds(courseScheduleDetailsId);
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的courseScheduleDetailsList: " + courseScheduleDetailsList);
        List<CourseAndTimeVo> resultList = new ArrayList<>();
        if (courseScheduleDetailsList != null && !courseScheduleDetailsList.isEmpty()) {
            for (CourseScheduleDetails course : courseScheduleDetailsList) {
                // 创建VO对象
                CourseAndTimeVo courseAndTimeVo = new CourseAndTimeVo();
                // 设置课程基本信息
                courseAndTimeVo.setCourseScheduleDetails(course);

                // 4. 查询当前课程的时间安排（关联class_schedule_detailed表）
                ClassScheduleDetailed timeQuery = new ClassScheduleDetailed();
                timeQuery.setCourseScheduleDetailsId(course.getId()); // 用课程ID关联时间安排
                List<ClassScheduleDetailed> timeList = classScheduleDetailedMapper.selectClassScheduleDetailedList(timeQuery);

                // 设置时间安排列表（即使为空也赋值，避免前端空指针）
                courseAndTimeVo.setClassScheduleDetailedList(timeList);

                // 添加到结果列表
                resultList.add(courseAndTimeVo);
            }
        }
        System.out.println("getCourseScheduleDetailsByTeacherId00获取到的resultList: " + resultList);
        return resultList;
    }
    /**
     * 通过原教师ID查询所有对应的调整记录
     * @param
     * @return 调整记录列表
     */
    @GetMapping("/selectAdjustmentRecordByOriginalTeacherId")
    public AjaxResult selectAdjustmentRecordByOriginalTeacherId() {
        LoginUser user = SecurityUtils.getLoginUser();
        String teacherId = "";
        teacherId = user.getUsername();
        teacher teacher =new teacher();
        teacher.setTeacherCode(teacherId);
        List<teacher> teacherList = teacherMapper.selectteacherList(teacher);
        teacher teacher1 = teacherList.get(0);
        String teacherId1 = teacher1.getUuid();
        System.out.println("selectAdjustmentRecordByOriginalTeacherId获取到的originalTeacherId: " + teacherId1);
        List<String> courseScheduleDetailsId = resourceAvailabilityService.selectCourseScheduleDetailsIdByResourceId(teacherId1);
        System.out.println("selectAdjustmentRecordByOriginalTeacherId获取到的courseScheduleDetailsId: " + courseScheduleDetailsId);
        List<CourseAdjustmentRecord> courseAdjustmentRecordList = courseAdjustmentRecordService.selectAdjustmentRecordByCourseScheduleDetailsIds(courseScheduleDetailsId);
        return AjaxResult.success(courseAdjustmentRecordList);
    }
    /**
     * 查询对应的调整记录
     * @param
     * @return 调整记录列表
     */
    @GetMapping("/selectAdjustmentRecord")
    public TableDataInfo selectAdjustmentRecord() {
        List<String> collegeIds = studentInfoService.selectCollegeCodesByDeptIds();
        System.out.println( "获取到的学院ID列表------collegeIds"+collegeIds);
        // 分页处理（建议放在判断前，确保两种分支都分页）
        //startPage();

        List<CourseAdjustmentRecord> list;
        // 处理collegeIds为null或空列表的情况
        if (CollectionUtils.isEmpty(collegeIds)) {
            list = courseAdjustmentRecordService.selectCourseAdjustmentRecordList(new CourseAdjustmentRecord());
        } else {
            // 根据学院ID列表查询
//            list = courseScheduleDetailsService.selectCourseScheduleDetailsByCollegeIds(collegeIds);
//            System.out.println( "课程排课详细列表---CourseScheduleDetails---list"+list);
            list = courseAdjustmentRecordMapper.selectAdjustmentByDepartmentIds(collegeIds);
        }
        return getDataTable(list);
    }

    /**
     * 根据courseScheduleDetailsId获取所有排课详细信息
     *
     * @param courseScheduleDetailsId 课程安排详情ID
     * @return 排课详细信息列表
     */
    @GetMapping("/getAllByCourseScheduleDetailsId/{courseScheduleDetailsId}")
    public ClassScheduleVo getAllByCourseScheduleDetailsId(@PathVariable String courseScheduleDetailsId) {
        ClassScheduleVo classScheduleVo = new ClassScheduleVo();
        CourseScheduleDetails courseScheduleDetails =courseScheduleDetailsService.selectCourseScheduleDetailsById(courseScheduleDetailsId);

        classScheduleVo.setClassScheduleDetailedList(classScheduleDetailedService.selectAllByCourseScheduleDetailsId(courseScheduleDetailsId));
        classScheduleVo.setCourseScheduleDetails(courseScheduleDetails);
        List<ResourceAvailability> resourceAvailabilityList =resourceAvailabilityService.selectByResourceIdAndAcademicYear(courseScheduleDetailsId,1);
        List<String> teacherIds = new ArrayList<>();
        for (ResourceAvailability resourceAvailability : resourceAvailabilityList) {
            teacherIds.add(resourceAvailability.getResourceId());
        }
        classScheduleVo.setTeacherIds(teacherIds);
        return classScheduleVo;
    }
    @GetMapping("/CourseScheduleDetailsList")
    public TableDataInfo CourseScheduleDetailsList() {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取用户角色列表
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(loginUser.getUserId());

        // 标记角色类型
        boolean isAdminOrGraduateOffice = userRoles.stream()
                .anyMatch(role -> "admin".equals(role.getRoleKey()) || "GraduateOffice".equals(role.getRoleKey()));
        boolean isTeacher = userRoles.stream()
                .anyMatch(role -> "teacher".equals(role.getRoleKey()));

        List<CourseScheduleDetails> list;
        if (isAdminOrGraduateOffice) {
            // admin或GraduateOffice角色：全量加载数据
            CourseScheduleDetails courseScheduleDetails = new CourseScheduleDetails();
            list = courseScheduleDetailsService.selectCourseScheduleDetailsList(courseScheduleDetails);
        } else if (isTeacher) {
            // teacher角色：使用教师专属方法加载数据
            list = resourceAvailabilityService.selectCourseScheduleDetailsIdByTeacherCode(loginUser.getUsername());
        } else {
            // 研究生秘书角色：返回对应学院的课程安排列表
            List<String> collegeIds = studentInfoService.selectCollegeCodesByDeptIds();
            list = courseScheduleDetailsMapper.selectScheduleDetailsByCollegeIds(collegeIds);
        }

        return getDataTable(list);
    }

    /**
     * 根据课程班ID获取教师姓名列表
     * @param courseScheduleDetailsId 课程班详情ID
     * @return 教师姓名列表
     */
    @GetMapping("/getTeacherNamesByCourseScheduleDetailsId")
    public List<String> getTeacherNamesByCourseScheduleDetailsId(@RequestParam String courseScheduleDetailsId) {
        try {
            System.out.println("开始查询课程班教师名单，课程班ID: " + courseScheduleDetailsId);

            // 1. 根据课程班ID和资源类型1(教师)查询资源占用记录
            List<ResourceAvailability> resourceAvailabilityList = resourceAvailabilityService.selectByResourceIdAndAcademicYear(courseScheduleDetailsId, 1);

            if (CollectionUtils.isEmpty(resourceAvailabilityList)) {
                System.out.println("未找到该课程班的教师资源记录");
                return Collections.emptyList();
            }

            // 2. 提取教师ID并去重
            Set<String> teacherIds = new HashSet<>();
            List<String> teacherNames = new ArrayList<>();

            for (ResourceAvailability resourceAvailability : resourceAvailabilityList) {
                String teacherId = resourceAvailability.getResourceId();
                if (StringUtils.isNotEmpty(teacherId)) {
                    teacherIds.add(teacherId);
                }
            }

            System.out.println("获取到的教师ID列表: " + teacherIds);

            // 3. 根据教师ID查询教师姓名
            for (String teacherId : teacherIds) {
                teacher teacher = teacherService.selectteacherByUuid(teacherId);
                if (teacher != null && StringUtils.isNotEmpty(teacher.getName())) {
                    teacherNames.add(teacher.getName());
                }
            }

            System.out.println("获取到的教师姓名列表: " + teacherNames);

            return teacherNames;

        } catch (Exception e) {
            logger.error("查询课程班教师名单失败", e);
            // 发生异常时返回空列表
            return Collections.emptyList();
        }
    }
}
